package dao;

import bean.Task;
import util.JDBCutil;
import util.SQLUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class TaskDao {
    private Connection connection = JDBCutil.getConnection();

    public List<Task> taskList() {
        List<Task> list = new ArrayList<>();
        String sql = "SELECT * FROM task";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet set = ps.executeQuery();
            while (set.next()) {
                Task task = new Task();
                task.setId(set.getInt("task.id"));
                task.setName(set.getString("task.name"));
                task.setSummary(set.getString("task.summary"));
                list.add(task);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int addTask(Task task) {
        int row = 0;
        String sql = "INSERT INTO task (name,summary) VALUES (?,?);";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, task.getName());
            ps.setString(2, task.getSummary());
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    public Task getTask(int id) {
        String sql = "SELECT * FROM task WHERE id=?";
        Task task = new Task();
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet set = ps.executeQuery();
            while (set.next()) {
                task.setId(set.getInt("id"));
                task.setName(set.getString("name"));
                task.setSummary(set.getString("summary"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return task;
    }

    public int deleteTask(int id) {
        int row = 0;
        String sql = "DELETE FROM task WHERE id=?";
        row = SQLUtil.deleteInfo(sql, id);
        return row;
    }

    public int updateTask(Task task) {
        int row = 0;
        String sql = "UPDATE task SET name= ?,summary=?  WHERE id=? ;";
        System.out.println("task = " + task.toString());
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, task.getName());
            ps.setString(2, task.getSummary());
            ps.setInt(3, task.getId());
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

}
